﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TWarehouseRepository : BaseRepository<TWarehouse>, ITWarehouseRepository
    {
        public TWarehouseRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }


        /// <summary>
        /// 添加库房
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool AddWarehouse(TWarehouse m)
        {

            m.CreateDate = DateTime.Now;
            m.ModifyDate = DateTime.Now;
                    
            m.ModifyUserName = m.CreateUserName;
            Context.TWarehouses.Add(m);
            return Context.SaveChanges()>0;
        }

        public bool DelTWarehouse(int id)
        {
            try
            {
                var wh = Context.TWarehouses.Find(id);
                if (wh is not null)
                {
                    Context.TWarehouses.Remove(wh);
                    return Context.SaveChanges() > 0;
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public List<TWarehouse> GetAllTWarehouse(string? name, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var whList = Context.TWarehouses.AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    whList = whList.Where(c => c.Name.Contains(name));
                }
                totalCount = whList.Count();
                whList = whList.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                return whList.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public TWarehouse GetTWarehouseById(int id)
        {
            try
            {
                return Context.TWarehouses.Find(id);
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool UpdTWarehouse(TWarehouse wh)
        {
            try
            {
                wh.ModifyDate = DateTime.Now;
                wh.ModifyUserId = wh.NowUserId;
                wh.ModifyUserName = wh.NowUserRealName;
                Context.TWarehouses.Update(wh);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
